import { login, logout} from '@/api/system/login'
import { getInfo } from '@/api/system/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  id:'',
  username:'',
  name: '',
  isSubAccount: '',
  avatar: '',
  isLogin:false,
  /* introduction: '', */
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_IS_SUB_ACCOUNT: (state, isSubAccount) => {
    state.isSubAccount = isSubAccount
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
/*  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  }, */
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  IS_LOGIN: (state, isLogin) => {
    state.isLogin = isLogin
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.result.token)
        setToken(response.result.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit}) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {


        const { result } = response
        if (!result) {
          reject('Verification failed, please Login again.')
        }

        //commit('SET_ROLES', roles)
        commit('IS_LOGIN', true)
        commit('SET_ID', result.id)
        commit('SET_NAME', result.name)
        commit('SET_USERNAME', result.username)
        commit('SET_IS_SUB_ACCOUNT', result.isSubAccount)

        if(result.avatar){
          commit('SET_AVATAR', result.avatar)
        }else{
          commit('SET_AVATAR',  require("@/assets/avatar/bingdundun.png"))
        }
        //commit('SET_INTRODUCTION', introduction)
        resolve(result)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {

        commit('IS_LOGIN', false)
        commit('SET_ID', '')
        commit('SET_NAME', '')
        commit('SET_USERNAME', '')
        commit('SET_IS_SUB_ACCOUNT', '')
        commit('SET_AVATAR', '')

        removeToken()
        resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  updateLoginStatus({ commit, state }, isLogin) {
    commit('IS_LOGIN', isLogin)
    if (isLogin) {
      const loginUser = store.get(LOCAL_USER_KEY)
      commit('SET_NAME', loginUser.name)
      commit('SET_ORG', loginUser.org)
      state.username = loginUser.username
      state.userId = loginUser.id
      state.isAgree = loginUser.agree === '1'
      state.isSupplier = loginUser.org && loginUser.org.type === ORG_TYPE.SUPPLIER
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
